/**
 * useage
 * 
 * this.use("emmitter");
 * 
 * //全局触发器
 * this.emmiter.on("login",function(opts){...});
 * this.emmiter.emit("login",opts);
 * 
 * //局部触发器(组件内使用)
 * this.emmiter.on("login",function(opts){...},true);
 * this.emmiter.emit("login",opts,true);
 * 
 */

;(function(){
	var emitters_global = {};
	H5x.plugin("emitter",function(component){
		var emitters = {};
		component.emitter = new Emitter(component);
	});

	function Emitter(component){
		this.component = component;
		this.emitters = {};
	}

	Emitter.prototype = {
		on:function(name,action,scope){
			var component = this.component;
			var emts = scope?this.emitters:emitters_global;
			if(!emts[name]){
				emts[name] = [];
			}

			emts[name].push(action);
		},

		off : function(name,action,scope){
			var emts = scope?this.emitters:emitters_global;
			if(typeof action == "boolean"){
				scope = action;
				action = null;
			}

			var actions = emts[name]||[];

			if(!action){
				emts[name] = [];
			}else{
				actions.forEach(function(action_,index){
					if(action_ == action){
						actions.splice(index,1);
					}
				});
			}
			
			
		},

		emit:function(name,opts,scope){
			var args = Array.prototype.slice.call(arguments);
			args.shift();
			var component = this.component;
			var emts = scope?this.emitters:emitters_global;

			var actions = emts[name]||[];

			//console.log(args);
			
			actions.forEach(function(action){
				action.apply(component,args);
			});
		}

		
	}
})();
